package com.lry.util.requestcore.handler.parse;

import cn.hutool.core.util.XmlUtil;
import com.lry.util.requestcore.handler.StringParser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;

/**
 * xml解析器
 *
 * @author ALI
 * @since 2023/5/8
 */
@Slf4j
public class XmlParser extends StringParser {

    @Override
    public Object parserObj(String data) {
        List<Map<String, Object>> objects = parseList(data);
        if (objects.isEmpty()) {
            return "";
        }
        return objects.get(0);
    }

    @Override
    public List<Map<String, Object>> parseList(String xmlStr) {
        Map<String, Object> map = XmlUtil.xmlToMap(xmlStr);
        if (map == null || map.isEmpty()) {
            return Collections.emptyList();
        }
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!entry.getKey().contains("Body")) {
                continue;
            }
            Object value = entry.getValue();
            // 方法
            for (Map.Entry<String, Object> mothod : ((Map<String, Object>) value).entrySet()) {
                Object data = mothod.getValue();
                if (data instanceof Map) {
                    Map<String, Object> temp = (Map<String, Object>) data;
                    for (Map.Entry<String, Object> entityEntry : temp.entrySet()) {
                        Object entityObj = entityEntry.getValue();
                        // 这里可能时Map也或者时String
                        result.add((Map<String, Object>) entityObj);
                    }
                } else {
                    log.info("不符合规范的soap格式");
                }
            }
        }
        return result;
    }
}
